﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CB.KM.ZH.ReceivableClearInvoiceQty
{
    [Description("应收单清空发票数量"), HotUpdate]
    public class ClearInvoiceQtyOfList : AbstractListPlugIn
    {
        public string btype { get; set; } = "应收单清空发票数量";
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            if (e.BarItemKey.EqualsV1("btnClearInvoiceQty"))
            {
                try
                {
  
                    var lv = this.View as IListView;
                    if (lv == null)
                    {
                        View.ShowErrMessage($@"无数据!!!");
                        return;
                    }
                    var selectedRows = lv.SelectedRowsInfo;
                    if (selectedRows == null || selectedRows.Count == 0)
                    {
                        this.View.ShowMessage("当前没有行被选中！");
                        return;
                    }
                    List<int> ids = selectedRows.Select(x => x.PrimaryKeyValue.ToStringV1().ToInt32V1()).Distinct().ToList();
                    if (ids.Count < 1)
                    {
                        View.ShowErrMessage($@"选择行为空!!!");
                        return;
                    }
                    int size = 5000;
                    int icount = ids.Count <= size ? 1 : ids.Count % size > 0 ? ids.Count / size + 1 : ids.Count / size;
                    for (int i = 0; i < icount; i++)
                    {
                        List<int> idList = ids.Skip(i * size).Take(size).ToList();
                        string sql = $@"/*dialect*/ update enty set FBUYIVQTY=0,FBUYIVBASICQTY=0,FIVALLAMOUNTFOR=0
from t_AR_receivableEntry enty
inner join t_AR_receivable main on enty.FID=main.FID
where enty.FID in ({string.Join(",", idList)}) and main.FDOCUMENTSTATUS='C'";
                        DBUtils.Execute(Context, sql);
                    }
                    View.Refresh();
                }
                catch (Exception ex)
                {
                    View.ShowErrMessage(ex.Message);
                }
            }
        }
    }
}
